package com.metaverse.backend.task;

import cn.hutool.core.date.DateUtil;
import com.metaverse.backend.domain.LiveLike;
import com.metaverse.backend.repo.LiveLikeRepo;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;


/**
 * 定时更新token
 */
@Slf4j
@AllArgsConstructor
@Service
public class LiveLikeSaveTask {


    private LiveLikeRepo liveLikeRepo;
    /**
     * 30秒执行一次
     *
     */
    @Scheduled(fixedDelay = 30L * 1000L)
    public void updateToken(){
        log.info("定时更新抖音点赞数据：" );
        save();
    }

    public void save() {
        int i=0;
        List<LiveLike> list = new ArrayList<>();
        while (Constant.LiveLikelist.size() > 0) {
            LiveLike item = Constant.LiveLikelist.poll();
            if (item != null) {
                //转换发生时间
                if (item.getTimestamp() != null) {
                    //转换发生时间
                    LocalDateTime happenTime = DateUtil.date(item.getTimestamp()).toLocalDateTime();
                    item.setHappenTime(happenTime);
                }
                list.add(item);
                i++;
            }
            if (list.size() > 500) {
                liveLikeRepo.saveAll(list);
                list.clear();
            }
        }
        if (list.size()>0){
            liveLikeRepo.saveAll(list);
        }
        if (i>0){
            log.info("定时更新抖音点赞数据：{}",i );
        }
    }

}
